package com.jswlw.common.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class XmlUtils {
    private static final String HEAD = "head";
    private static final String BODY = "body";


    public static void main(String[] args) throws DocumentException {
        String xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "<return_msg><![CDATA[OK]]></return_msg>\n" +
                "<appid><![CDATA[wx43d557c3c531f968]]></appid>\n" +
                "<mch_id><![CDATA[1494408192]]></mch_id>\n" +
                "<nonce_str><![CDATA[vCckPkoaGcuTqHGj]]></nonce_str>\n" +
                "<sign><![CDATA[3B6B3224C366512D49A6337F7D086078]]></sign>\n" +
                "<result_code><![CDATA[FAIL]]></result_code>\n" +
                "<err_code><![CDATA[INVALID_REQUEST]]></err_code>\n" +
                "<err_code_des><![CDATA[201 商户订单号重复]]></err_code_des>\n" +
                "</xml>";
        System.out.println(readStringXmlOut(xml).toString());
    }


    /**
     * @description 将xml字符串转换成map
     * @param xml
     * @return Map
     */
    public static Map<String, String> readStringXmlOut(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            @SuppressWarnings("unchecked")
            List<Element> list = rootElt.elements();// 获取根节点下所有节点
            for (Element element : list) { // 遍历节点
                map.put(element.getName(), element.getText()); // 节点的name为map的key，text为map的value
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


}